package com.wanghlme.day26.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//封装相同的代码到方法里
public class DBUtil {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
	static{//静态代码块,初始化类;类加载的时候执行1次
		//读取数据
		Properties props=new Properties();
		InputStream inStream=DBUtil.class.getClassLoader()
				.getResourceAsStream("db.properties");
		try {
			props.load(inStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
		driver=props.getProperty("driver");
		url=props.getProperty("url");
		user=props.getProperty("user");
		password=props.getProperty("password");
	}
	//获取连接
	public static Connection getConn(){
		Connection conn=null;
		try {
			Class.forName(driver);
			conn=DriverManager.getConnection(url, user, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	//释放资源
	public static void closeAll(ResultSet rs,Statement stmt,Connection conn){
		try {
			if(rs!=null)
				rs.close();
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}finally{
			try {
				if(stmt!=null)
					stmt.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}finally{
				try {
					if(conn!=null){
						conn.close();
					}
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
